﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Guedes_Library;
using System.IO;
using AjaxControlToolkit;

namespace AdmBase
{
    public abstract class TelaBase : System.Web.UI.Page
    {
        private UsuarioBusiness usuarioBusiness;

        private AsyncFileUpload file;

        private String urlArquivo;

        private String urlThumb;

        public String UrlThumb
        {
            get { return urlThumb; }
            set { urlThumb = value; }
        }

        public String UrlArquivo
        {
            get { return urlArquivo; }
            set { urlArquivo = value; }
        }

        public AsyncFileUpload File
        {
            get { return file; }
            set { file = value; }
        }

        protected UsuarioBusiness UsuarioBusiness
        {
            get
            {
                if (usuarioBusiness == null)
                    usuarioBusiness = new UsuarioBusiness();
                return usuarioBusiness;
            }
            set { usuarioBusiness = value; }
        }
        
        protected Boolean ValidaUsuario(String email, String senha)
        {
            return UsuarioBusiness.ValidaUsuario(email,senha);
        }

        protected String DoLogin(String email, String senha)
        {
            String msg = "";
            if (UsuarioBusiness.ValidaUsuario(email, senha))
            {
                Session["usuario"] = UsuarioBusiness.Usuario;
                Response.Redirect("~/admin/pages/Default.aspx");
            }
            else
            {
                msg = "Usuáro ou senha incorreto!";
            }
            return msg;
        }

        public void IsLogado()
        {
            Usuario usuario = GetUsuarioSessao();
            if (!UsuarioBusiness.IsLogado(usuario))
            {
                Response.Redirect("~/admin/");
            }
        }

        public void DoLogOff()
        {
            Session.RemoveAll();
            Response.Redirect("~/");
        }


        public Usuario GetUsuarioSessao()
        {
            return (Usuario) Session["usuario"];
        }

        public void ShowMensagem(String tiulo, String conteudo)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "teste", "mensagem.alerta('" + tiulo + "','" + conteudo + "')", true);
        }


        public void  UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {


            // Uncomment to save to AsyncFileUpload\Uploads folder.
            // ASP.NET must have the necessary permissions to write to the file system.

            //Cria nome único para arquivo
            string uniquefilename = string.Format("{0}{1}", DateTime.Now.Ticks, Path.GetExtension(e.FileName));
            //pega o diretorio para onde o arquivo vai ser veio o upload
            string savePath = MapPath("~/File/" + uniquefilename);
            string thumbPath = MapPath("~/File/thumb/" + uniquefilename);

            UrlThumb =  UrlArquivo = uniquefilename;

            SalvarArquivo(savePath);
            ResizeImage(savePath, thumbPath, 100, 62, true);
       }

        public void UploadedFileError(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
           ShowMensagem("Erro no envio",e.StatusMessage);
        }

        public void SalvarArquivo(String path)
        {
            file.SaveAs(path);
            DoReturnPage();
        }

        // Sobreescrever esse metodo para passar o retorno para página
        public virtual void DoReturnPage() 
        { 
        
        }

        //GERA THUMB NOVO
        public void ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
        {
            System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);

            // Prevent using images internal thumbnail
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
            FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

            if (OnlyResizeIfWider)
            {
                if (FullsizeImage.Width <= NewWidth)
                {
                    NewWidth = FullsizeImage.Width;
                }
            }

            int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
            if (NewHeight > MaxHeight)
            {
                // Resize with height instead
                NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
                NewHeight = MaxHeight;
            }

            System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

            // Clear handle to original file so that we can overwrite it if necessary
            FullsizeImage.Dispose();


            // Save resized picture
            NewImage.Save(NewFile);
        }


        public void ApagarArquivo(string url)
        {   
            string url_arquivo = MapPath(url);
            // Apaga arquivo principal
            if (!url.Equals("") &&  System.IO.File.Exists("~/File/"+url_arquivo))
            {
                System.IO.File.Delete(url_arquivo);
            }

            // Apaga banner
            if (!url.Equals("") && System.IO.File.Exists("~/File/thumb/"+url_arquivo))
            {
                System.IO.File.Delete(url_arquivo);
            }

        }

    }
}
